/**
 * 匿名拨打
 * @param {String} phone
 * @return {Object} 执行结果
 * 
 */
async function call(phone) {
	// 验证手机号格式
	if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
		return $.ret.error(10000, "请输入正确的手机号码");
	}

	// 隐藏中间4位数字
	// var maskedPhone = phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");

	return $.ret.obj({
		phone
	});
}

/**
 * 接口主函数
 * @param {Object} ctx HTTP上下文
 * @param {Object} db 数据管理器,如: { next: async function{}, ret: {} }
 * @return {Object} 执行结果
 */
async function main(ctx, db) {
	// 获取请求参数
	var req = ctx.request;
	var {
		query,
		body
	} = req;

	var user = await this.get_state(ctx, db) || {
		user_id: 0
	};

	// 操作sql模板
	var m = query.method;
	if (m === "call") {
		return await call(query.phone);
	} else if (m === "add") {
		if (user.gm < 3) {
			// 只允许用户给自己添加挪车信息
			body.user_id = user.user_id;
		} else if (!body.user_id) {
			if (body.phone) {
				var dbu = db.new("user_account", "user_id");
				var u = await dbu.getObj({
					phone: body.phone
				});
				if (!u) {
					var bl = await dbu.add({
						phone: body.phone,
						email: body.email
					});
					if (bl <= 0) {
						return $.ret.error(10000, "创建失败!");
					}
				}
				if (u) {
					body.user_id = u.user_id;
				}
			}
		}
	} else if (m === "del") {
		if (!user) {
			return $.ret.error(60000, "登录后才能操作!");
		}
		// 只允许用户删除自己的挪车信息
		query.user_id = user.user_id;
	} else if (m === "set") {
		if (!user) {
			return $.ret.error(60000, "登录后才能操作!");
		}
		body.user_id = user.user_id;
		var car_id = query.car_id || body.car_id;
		if (car_id) {
			var db1 = db.new("tool_move_car", "car_id");
			var car = await db1.getObj({
				car_id
			});
			if (car) {
				if (car.user_id) {
					if (car.user_id !== user.user_id) {
						return $.ret.error(70001, "不能修改别人的挪车信息!");
					}
				}
			} else {
				Object.assign(body, {
					car_id,
					user_id: user.user_id
				})
				var bl = await db1.add(body);
				if (bl) {
					return $.ret.bl(true, "绑定成功");
				}
			}
		}
	} else {
		var {
			car_id,
			timestamp,
			signature,
			keyword
		} = query;
		if (!car_id && !keyword) {
			if (user) {
				if (!user.gm) {
					query.user_id = user.user_id;
				}
			} else {
				return $.ret.error(60000, "登录后才能查看!");
			}
		}
		// 	// 安全码
		// 	var salt = "asd123";
		// 	var plug = this.plugin();
		// 	if (plug) {
		// 		var options = plug.get_options();
		// 		salt = options.salt;
		// 	}
		// 	var sign = (car_id + timestamp + salt).md5();
		// 	if (signature !== sign) {
		// 		return $.ret.error(10000, "签名错误!");
		// 	}
		// 	delete query.timestamp;
		// 	delete query.signature;
		// }
	}
	var ret = await this.sql.run(query, body, db);
	if (m === "add" && ret.result) {
		var db1 = db.new("tool_move_car", "car_id");
		var car = await db1.getObj({}, '`car_id` desc');
		var plug = this.plugin();
		if (plug) {
			var options = plug.get_options();
			options.start_car_id = car.car_id + 1;
		}
	}
	return ret;
};

exports.main = main;